<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/13 0013
 * Time: 13:41
 */

namespace logic\jihuo\driver;

use core\Msg;
use logic\LogicException;
use api\Checkapi;
use core\Rand;
use mod\DynamicPrize;
use mod\Lianpiao;
use mod\User;
use mod\Zuhe;
use mod\Zuhesp;

class Normal extends Base
{
	public function pc($data = array() , $userInfo = array())
	{
	}

	public function mobile($data = array() , $userInfo = array())
	{
		$this -> setSource( 'mobile' );
		empty($this->data) && $this -> setData( $data );
		empty($this->userInfo) && $this -> setUserInfo( $userInfo );

		if (!isCreditNo($this->data['shenfenid'])) {
			throw new LogicException($this->msg['shenfenid']);
		}

		//根据联票号获取联票全部信息
		$this->checkLianpiaoIsjihuo();
		$this->checkLianpiao();
		$this->checkCardCount();
		$this->phoneActivationNum();

		//判断批号是否激活
		$this->checkPihao();

		//绑定会员账号uid
		$this->bindUser();
	}

	public function admin($data = array() , $userInfo = array())
	{
		$this -> setSource( 'admin' );
		empty($this->data) && $this -> setData( $data );
		empty($this->userInfo) && $this -> setUserInfo( $userInfo );

		if (isset($this->data['isvalidate'])) {
			if (!isCreditNo($this->data['shenfenid'])) {
				throw new LogicException($this->msg['shenfenid']);
			}
			unset($this->data['isvalidate']);
		}

		//根据联票号获取联票全部信息
		$this->checkLianpiaoIsjihuo();
		$this->checkLianpiao();
		$this->checkCardCount();
		$this->phoneActivationNum();

		//判断批号是否激活
		$this->checkPihao();

		//绑定会员账号uid
		$this->bindUser();
	}

	public function edit($data = array() , $userInfo = array())
	{
		$this -> setSource( 'admin' );
		empty($this->data) && $this -> setData( $data );
		empty($this->userInfo) && $this -> setUserInfo( $userInfo );

		if (isset($this->data['isvalidate'])) {
			if (!isCreditNo($this->data['shenfenid'])) {
				throw new LogicException($this->msg['shenfenid']);
			}
			unset($this->data['isvalidate']);
		}

		//根据联票号获取联票全部信息
		$this->checkLianpiao();
		if($this->lianpiaoResult['isjihuo'] <> 10){
			throw new LogicException('连票号码没有激活');
		}
		$this->checkCardCount(false);
		$this->phoneActivationNum(false);
		//判断批号是否激活
		$this->checkPihao();

		//更新预定人信息
		$upd = array();
		$upd [ 'username' ]     = $this->data[ 'username' ];       // 获得用户姓名
		$upd [ 'phone' ]        = $this->data[ 'phone' ];      // 用户电话
		$upd [ 'shenfenid' ]    = $this->data[ 'shenfenid' ];    // 获得身份证号
		$upd [ 'sex' ]          = $this->data[ 'sex' ];         // 性别
		$upd [ 'province' ]     = $this->data[ 'province' ];
		$upd [ 'city' ]         = $this->data[ 'city' ];
		$upd [ 'town' ]         = $this->data[ 'town' ];
		$status = Lianpiao::where("id", $this->lianpiaoResult['id'])->update($upd); // 修改
		if ($status < 0) {
			throw new LogicException($this->msg['save_lianpiao']);
		}
	}

	/*
	 * 纯抽奖类，激活时不需要填写用户的详细信息
	 */
	public function simple($data = array() , $userInfo = array())
	{
		$this -> setSource( 'mobile' );
		empty($this->data) && $this -> setData( $data );
		empty($this->userInfo) && $this -> setUserInfo( $userInfo );

		//设置空置数据
		$this->data['username']     =  '';
		$this->data['phone']        =  $this->userInfo['phone'];
		$this->data['shenfenid']    =  '';
		$this->data['province']     =  '';
		$this->data['city']         =   0;
		$this->data['town']         =   0;
		$this->data['isjihuo']      =  10;
		$this->data['sex']          =  '';

		//根据联票号获取联票全部信息
		$this->checkLianpiaoIsjihuo();
		$this->checkLianpiao();
		$this->phoneActivationNum();

		//判断批号是否激活
		$this->checkPihao();

		//绑定会员账号uid
		$this->bindUser();
	}


	/*
	 * 激活操作
	 */
	public function jihuoOperation(){
		$this->data['uid'] = $this->bindUserId;
			//更新预定人信息
		$status = Lianpiao::where("id", $this->lianpiaoResult['id'])->update($this->data); // 修改
		if ($status < 0) {
			throw new LogicException($this->msg['save_lianpiao']);
		}

		//添加固定奖劵
		$this->dynamicPrize();
	}

	/*添加固定奖劵*/
	public function dynamicPrize(){
		$zuhespModel = new Zuhesp();
		$zuhesp = $zuhespModel
			->where('zuhe_id',$this->lianpiaoResult['zuhe_id'])
			->where('fixed',1)
			->select();
		if( !empty($zuhesp) ){
			$data = array();
			$dataAll = array();
			foreach ($zuhesp as $d){
				$data['lianpiao_id']        = $this->lianpiaoResult['id'];
				$data['lianpiaono']         = $this->lianpiaoResult['lianpiaono'];
				$data['travel_id']          = $d['travel_id'];
				$data['addtime']            = date('Y-m-d H:i:s');
				$data['starttime']          = $d['starttime'];
				$data['endtime']            = $d['endtime'];
				$data['zuhe_id']            = $this->lianpiaoResult['zuhe_id'];
				$data['com_id']             = $this->lianpiaoResult['com_id'];
				$data['pihao_id']           = $this->lianpiaoResult['pihao_id'];
				$data['prize_coupon_code'] = Rand::str(20);
				$data['type']               = 2;
				$data['uid']                = $this->bindUserId;
				$dataAll[] = $data;
			}
			$dynamicPrizeModel = new DynamicPrize();
			$dynamicPrizeModel->insertAll($dataAll);
		}
	}


	/**
	 * 激活不预约订单操作入库
	 */
	public function noRestionOperation(){

		$ydsp['phone'] = $this->data['phone'];
		$ydsp['worker'] = $this->data['username'];
		$ydsp['lianpiao_id'] = $this->lianpiaoResult['id'];
		$ydsp['lianpiaono'] = $this->lianpiaoResult['lianpiaono'];
		$ydsp['yudingtime'] = date("Y-m-d",strtotime("+1 day"));
		//$ydsp['endyudingtime'] = date("Y-m-d",strtotime("+365 day"));
		$ydsp['endyudingtime'] = $this->data['shiyongdate'];
		$ydsp['shenfenzheng'] = $this->data['shenfenid'];
		$ydsp['yudingrenid'] = 0;
		$ydsp['addtime'] = date('Y-m-d H:i:s');
		$ydsp['zuhe_id'] = $this->lianpiaoResult['zuhe_id'];
		$ydsp['pihao_id'] = $this->lianpiaoResult['pihao_id'];
		$ydsp['yudingrenname']="系统";

		$port = \api\CheckApi::getinstance();

		$jtsp = db("zuhesp")->alias('a')->join("travel b", "a.sp_id=b.aid")
			->where("a.zuhe_id", $this->lianpiaoResult['zuhe_id'])->where("a.no_restion", 1)
			->field("b.api_id,b.title,b.aid,b.father_travel")
			->select();

		foreach ($jtsp as $sp => $value) {
			$ydsp['jqname'] = $value['title'];
			$ydsp['jqid'] = $value['aid'];
			$ydsp['sp_id'] = $value['aid'];
			//子景区预定判断
			if($value['father_travel']>0){
				$ydsp['check_travel']=$value['father_travel'];
			}else{
				$ydsp['check_travel']=$value['aid'];
			}
			$orders= db('yuding')->insertGetId($ydsp);

			//开始向API实时发送预订数据
			$source = $this->sourceMsg;
			$dsOrderCode=$orders.time();
			$orderInfo['dsOrderCode']=$dsOrderCode;
			$orderInfo['sign'] = "c32de88944cfda16c8bb0119fe3e1b56";
			$orderInfo['yuding_id'] = $orders;
			$orderInfo['productId'] = $value['api_id'];
			$orderInfo['cradNo'] = $ydsp['shenfenzheng'];
			$orderInfo['name'] = $ydsp['worker'];
			$orderInfo['phone'] = $ydsp['phone'];
			$orderInfo['playDate'] = $ydsp['yudingtime'];
			$orderInfo['endPlayDate'] = $ydsp['endyudingtime'];
			$orderInfo['jqid'] = $value['aid'];
			$orderInfo['jqname'] = $value['title'];
			$orderInfo['lianpiaono'] = $ydsp['lianpiaono'];
			$orderInfo['addtime'] = date('Y-m-d H:i:s');

			$order['downstreamOrderCode']=$dsOrderCode;
			$order['cradNo']=$ydsp['shenfenzheng'];
			$order['name']=$ydsp['worker'];
			$order['phone']=$ydsp['phone'];
			$orderAll[]=$order;
			$flag_sendResult = $port->sendFreeOrder($value['api_id'],date("Y-m-d",strtotime("+1 day")),date("Y-m-d",strtotime("+365 day")),$orderAll,1,$source);

			$orderInfo['description'] = $port->result['description'];
			$orderInfo['code'] = $port->result['code'];

			$dataAll[]=$orderInfo;
			db('port_yuding')->insertAll($dataAll);
			unset($orderAll);

			//结束向API发送预订数据
		}
		
	}

	/**
	 * 操作记录日志
	 * 向记录表中添加记录
	 */
	public function addRecord()
	{
		empty($this->userInfo) && $this->getUserResult();
		//向记录表中添加记录
		$recorddata = array();
		$recorddata['content'] = '激活联票  联票号为:' . $this->lianpiaoResult['lianpiaono'];
		$recorddata['buid'] = $this->lianpiaoResult['id'];
		$recorddata['buname'] = $this->data['username'];
		$recorddata['uid'] = 0;
		$recorddata['username'] = '';
		$recorddata['ip'] = request()->ip();
		if(!empty($this->userInfo)) {
			$recorddata['username'] = $this->userInfo['nickname'];
			$recorddata['uid'] = $this->userInfo['uid'];
		}

		$recorddata['rtime'] = date('Y-m-d H:i:s');

		$recorddata['source'] = $this->sourceMsg;
		db('record')->insert($recorddata);
	}

	/**
	 * 个人联票永久缓存操作接口
	 * @param $key
	 * @param $value
	 */
	public function ssdb($key, $value)
	{
		$ssdb = new SimpleSSDB();
		if (strpos($key, ",") === false) {
			$valueStr = $ssdb->get(config('gobal.lianpiao') . $key);
			if ($valueStr == null) {
				$valueArr = [ $value ];
				$ssdb->set(config('gobal.lianpiao') . $key, json_encode($valueArr));
			} else {
				$valueArr = json_decode($valueStr, true);
				$valueArr[] = $value;
				$ssdb->set(config('gobal.lianpiao') . $key, json_encode($valueArr));
			}
		} else {
			$idArr = explode(",", $key);
			foreach ($idArr as $id) {
				$valueStr = $ssdb->get(config('gobal.lianpiao') . $id);
				if ($valueStr == null) {
					$valueArr = [ $value ];
					$ssdb->set(config('gobal.lianpiao') . $id, json_encode($valueArr));
				} else {
					$valueArr = json_decode($valueStr, true);
					$valueArr[] = $value;
					$ssdb->set(config('gobal.lianpiao') . $id, json_encode($valueArr));
				}
			}
		}
	}

	//调用短信
	public function sms($phone, $password){
		//您正在进行联票网注册操作，验证码：'.$msgCode.'，请输入此验证码，请勿泄露。【联票网】
		$content='尊敬的会员您好：您的手机号已经成功注册为联票会员，登录账号：'.$phone.'，密码：'.$password;

		$content=urlencode($content);
		//$Msg=new Msg();
		//$Msg->send($phone,$content,1);
	}

	public function getUserResult(){
		$userModel = new User();
		$userInfo = $userModel->field('uid,nickname,username,phone,rid,open_id')->where('uid',$this->userInfo['uid'])->find();
		$this->userInfo = array();
		$this->userInfo = $userInfo;
		!session('?user') && session('user',$userInfo);
	}

}